    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.logist;

import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.view.almac.*;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.service.ProductoService;
import dp1.titandevelop.titano.service.ValidacionService;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Yulian
 */
public class ModulosT_LOG_APDetalle extends javax.swing.JDialog {
    
    //Para el cbox
    private List<Producto> productos;
    private ArrayList<Integer> idprodnuevos;
    private ArrayList<Integer> idprodeditar;
    
    //Para agregar elementos al cbox    
    
    
    public boolean encontrado (int id, ArrayList<Integer> lista){
        for (int i = 0; i < lista.size(); i++){
            if (lista.get(i)== id){
                return true;
            }
        }
        return false;
    }
    public void RefrescarTabla() {
        AbstractTableModel aux = (AbstractTableModel) tblDetalle.getModel();
        aux.fireTableDataChanged();
    }
    

    private AbstractTableModel modeloTabla = new AbstractTableModel() {  
        
        private String [] titles = {"Insumo","Unidades"};
      
        public int getRowCount() {
            return productos.size();//tipos.size(); // cuantos registros (filas)
        }      
        
        public int getColumnCount() {
            return 2; // cuantas columnas
        }          
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }                
       
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object res=null;
            Producto p = productos.get(rowIndex);
            //boolean b = datos.get(rowIndex).seleccionado;//tipos.get(rowIndex);
            switch(columnIndex){
                case 0: res = p.getDescripcion();break;
                case 1: res = p.getUm(); break;
            }
            return res;
        } 
        @Override
        public boolean isCellEditable(int row, int col) {
            boolean res=false;
            switch (col) {
                case 0:break;
                case 1:break;
            }
            return res;
        }
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    };
    public ModulosT_LOG_APDetalle(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = this.getSize();
        this.setLocation((desktopSize.width - jInternalFrameSize.width-20),
                (desktopSize.height - jInternalFrameSize.height)/6);
        
        
        this.tblDetalle.setModel(modeloTabla);
        
        this.idprodeditar = new ArrayList<Integer>();
        this.idprodnuevos = new ArrayList<Integer>();
        
        ProductoService serv = new ProductoService();
        productos = serv.buscarInsumo();//Obtengos los insumos de la bd
    }
    public ModulosT_LOG_APDetalle(java.awt.Frame parent, boolean modal, List<Integer> idprodcs) {
        super(parent, modal);
        initComponents();
        
        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = this.getSize();
        this.setLocation((desktopSize.width - jInternalFrameSize.width-20),
                (desktopSize.height - jInternalFrameSize.height)/6);
        
        
        this.tblDetalle.setModel(modeloTabla);
        
        this.idprodeditar = new ArrayList<Integer>();
        this.idprodnuevos = new ArrayList<Integer>();
        
        ProductoService serv = new ProductoService();
        productos = serv.buscarInsumo();//Obtengos los insumos de la bd
        for(int i = 0; i<productos.size();i++){
            for (int j = 0 ; j < idprodcs.size(); j++){
                if (productos.get(i).getIdproducto() == idprodcs.get(j)){
                    productos.remove(i);
                }
            }
            
        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        btnOk = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblDetalle = new javax.swing.JTable();
        txtPrecio = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Asignar Insumo");

        btnOk.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/asignar.png"))); // NOI18N
        btnOk.setToolTipText("Agregar");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        btnCancelar.setToolTipText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista de Insumos"));

        tblDetalle.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Insumo", "Unidades", "Costo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblDetalle.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblDetalleMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblDetalle);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)
        );

        jLabel2.setText("Precio:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnOk)
                        .addGap(1, 1, 1)
                        .addComponent(btnCancelar)
                        .addGap(8, 8, 8)))
                .addGap(8, 8, 8))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(btnOk)
                        .addComponent(btnCancelar))
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2)))
                .addGap(8, 8, 8))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
        ValidacionService val = new ValidacionService();
        Mensajes m = new Mensajes();
        
        if (val.esVacio(txtPrecio)){
//            JOptionPane.showInternalMessageDialog(this.getRootPane(), m.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);

        }else{
        
        Producto p = productos.get(this.tblDetalle.getSelectedRow());
        if (ModulosT_LOG.ventanaNuevo != null){
//            if (this.encontrado(p.getIdproducto(), idprodnuevos)){   
//            }else {
//                this.idprodnuevos.add(p.getIdproducto());
                ModulosT_LOG.ventanaNuevo.addProducto(p.getIdproducto());
                ModulosT_LOG.ventanaNuevo.addPrecio(Float.parseFloat(this.txtPrecio.getText()));
                ModulosT_LOG.ventanaNuevo.RefreshTable();
                System.out.println("estoy ennuevp");
                this.productos.remove(this.tblDetalle.getSelectedRow());
                this.RefrescarTabla();
                this.txtPrecio.setText("");
//            }
            
        }
        else { 
            
            if (ModulosT_LOG.ventanaEdita != null){
//                if (this.encontrado(p.getIdproducto(), idprodeditar)){
//                 }else {
//                    this.idprodeditar.add(p.getIdproducto());
                    System.out.println("estoy editando");
                    ModulosT_LOG.ventanaEdita.addProducto(p.getIdproducto());
                    ModulosT_LOG.ventanaEdita.addPrecios(Float.parseFloat(this.txtPrecio.getText()));
                    ModulosT_LOG.ventanaEdita.RefreshTable();
                    this.productos.remove(this.tblDetalle.getSelectedRow());
                    this.RefrescarTabla();
                    this.txtPrecio.setText("");
//                }
            }
        }
        }
    }//GEN-LAST:event_btnOkActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void tblDetalleMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblDetalleMouseClicked
        this.txtPrecio.setText("");
    }//GEN-LAST:event_tblDetalleMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ModulosT_LOG_APNuevo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ModulosT_LOG_APNuevo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ModulosT_LOG_APNuevo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ModulosT_LOG_APNuevo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ModulosT_LOG_APDetalle dialog = new ModulosT_LOG_APDetalle(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnOk;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblDetalle;
    private javax.swing.JTextField txtPrecio;
    // End of variables declaration//GEN-END:variables
}
